package com.supervision.manage.service;

import com.fly.base.core.UserContext;
import com.fly.base.enums.ConstantKeyEnum;
import com.fly.base.exception.AuthFailException;
import com.fly.base.interceptor.SecurityInterceptor;
import com.supervision.domain.model.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 *
 * @author whis
 * @date 08/10/2016
 */
@Component("CoreAuthenticator")
public class UserAuthenticator implements SecurityInterceptor.Authenticator {

    private static Logger logger = LoggerFactory.getLogger(UserAuthenticator.class);

    private final TokenService tokenService;

    @Autowired
    public UserAuthenticator(TokenService tokenService) {
        this.tokenService = tokenService;
    }


    @Override
    public void process(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("accessToken");
        Token tokenModel = tokenService.getToken(token);
        if (tokenModel == null)
        {
            throw new AuthFailException("invalid token");
        }

//        tokenService.checkExpire(tokenModel);

        UserContext userContext = new UserContext();
        userContext.setUserId(tokenModel.getUserId());
        userContext.setUserType(tokenModel.getUserType());

        httpServletRequest.setAttribute(ConstantKeyEnum.REQUEST_ATTR_KEY_USER_CONTEXT.getValue(), userContext);

        // 判断路由权限
//        tokenService.veryApiUserAuth(tokenModel.getUserId(), httpServletRequest.getRequestURI());
    }
}
